import struct
import socket

from chat.common.RSA_file import *
from chat.client.client_database import *
import chat.client.gol


def get_socket_auth():
    print(chat.client.gol.get_value("socket_obj"))
    return chat.client.gol.get_value("socket_obj")


def get_recv(s):
    room_id = int.from_bytes(s.recv(4), 'little')
    data_type = int.from_bytes(s.recv(4), 'little')
    print("data_type =>",data_type)
    if data_type == 7:  # 获取room历史消息
        msg_num = int.from_bytes(s.recv(4), 'little')
        his_msg = []
        for msg_idx in range(msg_num):
            sender_id, time, msg_len = struct.unpack("<H19sQ", s.recv(2+19+8))
            time = time.decode()
            msg = s.recv(msg_len).decode()
            flag = s.recv(1)
            OTP_flag = int.from_bytes(flag, 'little')

            print("=====[room]=====")
            print("[sender_id] =>", sender_id)
            print("[time] =>", time)
            print("[msg] =>", msg)
            print("[OTP_flag] =>", OTP_flag)

            if (OTP_flag == 3):
                msg = "您收到一个文件，存放路径："+msg
            else:
                username = chat.client.gol.get_value("socket_username")
                privkey = int(return_room_private_key(username, room_id))
                n = int(return_room_private_key_n(username, room_id))
                msg = message_decryption(msg, privkey, n)
            his_msg.append((sender_id, time, msg))

        return his_msg


def socket_send_userid(users):
    """
    发送userid给server去创建room
    :param users:  数组类型，例如 [0, 2, 4] 前端返回+数据库查询本用户user_id
    :return:
    """

    server = get_socket_auth()
    user_data = b""
    user_num = 0
    socket_username = chat.client.gol.get_value("socket_username")
    print(" >>>> ", socket_username)
    self_id = get_user_id(socket_username)
    users.append(self_id)
    for user_id in users:
        user_data += struct.pack("<H", user_id)
        user_num += 1
    user_num = struct.pack("<H", user_num)
    data = user_num + user_data
    head = struct.pack("<i", len(data)) + b'\x04\x00\x00\x00'
    msg = head + data
    print("user_num ==>", user_num)
    print("user_data ==>", user_data)
    print("msg ==>", msg)
    server.send(msg)
    # get_recv(server)


def socket_get_room_history(room_id):
    server = get_socket_auth()
    data = struct.pack("<H", room_id)
    head = struct.pack("<i", 2)
    head += b'\x07\x00\x00\x00'
    msg = head+data
    print("msg ==>", msg)
    server.send(msg)
    return get_recv(server)

# chat.client.auth.auth.get_socket()
# users = [0, 3, 5, 8, 10]
# socket_send_userid(users)
